<template>
  <Layout.Content
    v-loading="contractConsoleCtx.contractClass?.state?.loading || false"
    class="contract-file-content contract-file-content-wrap overflow-auto p-6"
  >
    <div class="w-full 2xl:w-xl mx-auto mt-6">
      <Card class="!pr-1/2">
        <BasicTitle class="!pl-4 mb-6" span>合同基本信息</BasicTitle>
        <BasicForm @register="basicRegister" />
      </Card>
      <Card class="!pr-1/2 mt-6">
        <div class="w-full flex items-center mb-6">
          <BasicTitle class="!pl-4" span> 签署数据 </BasicTitle>
          <ApiSelect
            class="w-64 ml-4"
            v-bind="{
              api: getDoctorList,
              params: { ...searchValParams },
              resultField: 'content',
              labelField: 'name',
              valueField: 'id',
              'show-search': true,
              'filter-option': false,
              immediate: true,
              placeholder: '请选择签署人',
            }"
            @change="handleFormAccount"
            @search="(e) => (searchValParams.name = e)"
          />
        </div>
        <BasicForm @register="formRegister" />
      </Card>
    </div>
  </Layout.Content>
</template>

<script lang="ts" setup>
  import { Card, Layout } from 'ant-design-vue';
  import { ApiSelect, BasicForm, FormSchema, useForm } from '@/components/Form';
  import { basicSchemas } from '../consoleView.data';
  import { nextTick, ref, watch } from 'vue';
  import { BasicTitle } from '@/components/Basic';
  import { getDoctorList } from '@/api/public';
  import { dateUtil } from '@/utils/dateUtil';
  import { usePDFViewContext } from '../../pdf-view/hooks/usePDFViewContext';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicFormComponentKeys } from '@/components/Form/src/componentMap';

  const contractConsoleCtx = usePDFViewContext();
  const { createErrorModal } = useMessage();
  const [basicRegister, basicMethods] = useForm({
    schemas: basicSchemas,
    baseColProps: {
      span: 24,
    },
    showActionButtonGroup: false,
  });

  const [formRegister, formMethods] = useForm({
    schemas: ['doctorId', 'id'].map((el) => ({
      field: el,
      component: BasicFormComponentKeys.Input,
      show: false,
    })),
    baseColProps: {
      span: 24,
    },
    showActionButtonGroup: false,
  });

  const searchValParams = ref({ name: '' });

  watch(
    contractConsoleCtx.contractPdfInfo,
    (val) => {
      const res = val;
      if (!res || !res.id) return;

      basicMethods.setFieldsValue({
        file: res.address,
        title: res.contractName,
      });

      basicMethods.setProps({ disabled: true });

      try {
        const formJSON = (
          typeof res.field == 'string' ? JSON.parse(res.field) : res.field
        ) as Array<Record<string, any>>;

        const json = formJSON.map<FormSchema>((el) => {
          const { label, key } = el;

          return {
            field: key,
            label,
            component: BasicFormComponentKeys.Input,
            required: true,
          };
        });

        formMethods.setProps({
          schemas: json,
        });

        handleFormAccount(null, contractConsoleCtx.contractPdfInfo.value);
      } catch (error) {
        console.error(error);

        createErrorModal({
          title: '警告',
          content: '合同模板数据异常，请重试',
        });
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );

  watch(
    () => [basicMethods.validate, formMethods.validate],
    (val) => {
      contractConsoleCtx.validateForm = async () => {
        await Promise.all(val.map((el) => el()));

        contractConsoleCtx.contractPdfInfo.value = Object.assign(
          {},
          basicMethods.getFieldsValue(),
          formMethods.getFieldsValue(),
          {
            address: basicMethods.getFieldsValue().file.join(),
          },
        );
      };
    },
    {
      immediate: true,
      deep: true,
    },
  );

  async function handleFormAccount(e, item) {
    await nextTick();

    const self_form_props = await formMethods.getProps();

    self_form_props.fieldMapToTime?.forEach((el) => {
      const [field, df] = el;
      item[field] = df.map((el) => dateUtil(item[el]));
    });

    formMethods.setFieldsValue(item);
  }
</script>

<style lang="less" scoped>
  .contract-file-content-wrap {
    padding-top: @header-height;
    height: 100vh;
  }

  // .contract-file-content {}
</style>
